package vip.liux.contracts.shared.value;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public interface LevelModel<K extends LevelModel<?>> extends Serializable {

    List<K> getChildren();

    void setChildren(List<K> children);

    /**
     * 构建树形结构
     *
     * @param list              数据列表
     * @param idKeyMapper       id映射函数
     * @param parentIdKeyMapper 父id映射函数
     * @param <T>               数据类型
     * @return 树形结构
     */
    static <T extends LevelModel<T>> List<T> buildTree(
            List<T> list,
            Function<? super T, ?> idKeyMapper,
            Function<? super T, ?> parentIdKeyMapper
    ) {
        Map<?, T> map = list.stream().collect(Collectors.toMap(idKeyMapper, Function.identity()));
        List<T> roots = new ArrayList<>();
        for (T node : list) {
            Object parentId = parentIdKeyMapper.apply(node);
            if (parentId == null || !map.containsKey(parentId)) {
                roots.add(node);
            } else {
                T parent = map.get(parentId);
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(node);
            }
        }
        return roots;
    }


    /**
     * 辅助方法，用于递归展平树形结构
     *
     * @param node     当前节点
     * @param flatList 展平后的列表
     * @param <T>      数据类型
     */
    private static <T extends LevelModel<T>> void flattenTreeHelper(T node, List<T> flatList) {
        flatList.add(node);
        if (node.getChildren() != null) {
            for (T child : node.getChildren()) {
                flattenTreeHelper(child, flatList);
            }
        }
    }
}
